﻿<%@ WebHandler Language="C#" Class="URLRewriteMapping" %>

using System;
using System.Web;

//using System.Data;
using System.Reflection;


public class URLRewriteMapping : IHttpHandler 
{

    //public DataSet ds;
    //public URLRewriteMapping()
    //{
    //    try
    //    {

    //        ds = new DataSet();

    //        string path = //System.Web.HttpContext.Current.Server.MapPath("./Config.xml");
    //        HttpContext.Current.Server.MapPath(
    //            HttpContext.Current.Request.ApplicationPath + "/ServiceMapping.xml");
    //        ds.ReadXml(path);
    //    }
    //    catch (System.Exception ex)
    //    {

    //    }
    //}

    #region IHttpHandler 成员

    public void ProcessRequest(System.Web.HttpContext ctx)
    {
        
        ctx.Response.Charset = "UTF-8";

        //IIS RELEAS TEST
        //string errorPath = ctx.Request.RawUrl.Split(';')[1];
        //string appPath = ctx.Request.ApplicationPath;
        
        //ctx.Response.Write(errorPath);
        //ctx.Response.Write("<br/>");
        //int ipos = errorPath.IndexOf(appPath);
        //string url = errorPath.Substring(ipos + appPath.Length + 1);

        //ctx.Response.Write(url);
        
        //ctx.Response.Write("<br/>");
        //ctx.Response.Flush();
        //ctx.Response.End();
        //return;
        
        try
        {
            //RELEASE
            //string errorPath = ctx.Request.RawUrl.Split(';')[1];
            //DEBUG
            string errorPath = ctx.Request.RawUrl.Split('=')[1];
            //
            string appPath = ctx.Request.ApplicationPath;
            //获取服务器域名地址
            int ipos = errorPath.IndexOf(appPath);
            //获取要查询的URL，去除服务器域名
            string url = errorPath.Substring(ipos + appPath.Length + 1);
            //重写URL
            ctx.RewritePath("~/" + url);

            //DEBUG
            //string url = ctx.Request.RawUrl.Split('=')[1];

            //   if(!url.EndsWith("/"))
            //   {
            //      url+="/";
            //   }
            //   url+="index.html";
            //   context.Response.Write(url);
            //   context.RewritePath(url);

            //context.Response.Write(url);
            //url = "~" + url;

            //ctx.Response.Write("请求的路径:" + url);

            //string newUrl = lt.ReWriteModule.GetUrl(context, url);
            ////context.Response.Write(newUrl);
            //if (newUrl != null)
            //{
            //    //cxt.Response.Filter = new ResponseFilter(cxt.Response.Filter,cxt.Request.Path);

            //    ctx.Response.Write("<BR>");
            //    ctx.Response.Write("转向的目的URL：" + newUrl);
            //    ctx.Response.Write("<BR>");
            //    ctx.RewritePath(newUrl);
            //}
            //else
            //{
            //    ctx.Response.Write("你请求的资源不存在！！");
            //    ctx.Response.End();
            //}



            //
            //ds = new DataSet();

            //string path = //System.Web.HttpContext.Current.Server.MapPath("./Config.xml");
            //HttpContext.Current.Server.MapPath(
            //    HttpContext.Current.Request.ApplicationPath + "/ServiceMapping.xml");
            //ds.ReadXml(path);

            //
            //string name = ctx.Request.Url.AbsolutePath;
            //name = name.Substring(0, name.IndexOf('.'));
            //string name = url.Substring(0, url.IndexOf('.'));

            string[] namespaceArray = url.Split('/');
            string namespaceString = "";
            int classLen = namespaceArray.Length - 2;
            for (int iter = 0; iter < classLen; iter++)
            {
                namespaceString += namespaceArray[iter] + ".";
            }
            namespaceString = namespaceString.Substring(0, namespaceString.Length - 1);

            string className = namespaceArray[namespaceArray.Length - 2];
            string functionName = namespaceArray[namespaceArray.Length - 1];

            //
            //DataRow[] dc = ds.Tables[0].Select("url ='" + name + "'");
            //if (dc.Length > 0)
            //{
                //string className = dc[0]["Class"].ToString();
                
                //加载程序集空间
                //Assembly ass = Assembly.Load(
                //    className.ToString().Substring(0, className.LastIndexOf('.')));
                Assembly ass = Assembly.Load(namespaceString );
                //构建类型
                //Type ht = ass.GetType(dc[0]["Class"].ToString());
                Type ht = ass.GetType(namespaceString + "." + className);
                
                if(null == ht)//如果反射对象方法没有实现
                {
                    ctx.Response.Write("页面不存在！404 错误！");
                    ctx.Response.Flush();
                    return;
                    
                    //查找实体类命名空间
                    //ass = Assembly.Load("entity");
                    //获取此实体类类型
                    //ht = ass.GetType("entity." + className);
                    
                    //if(null == ht)//实体类都不存在
                    //{
                        
                    //    ht = ass.GetType("entity." + className);
                    //    formworks.ActionBase<Type.GetType(className)> xc = new 
                        
                        
                    //    ctx.Response.Write("页面不存在！404 错误！");
                    //    ctx.Response.Flush();
                    //    return;
                    //}                    
                }
                //发射创建对象
                object obj = Activator.CreateInstance(ht);
                
                //获取方法
                //MethodInfo mi = ht.GetMethod(dc[0]["function"].ToString());
                //MethodInfo[] mi = ht.GetMethods(functionName);
                MethodInfo mi = ht.GetMethod(functionName);
                //设置委托的方法的request参数

                //object objRtn = mi[0].Invoke(obj, new object[] { ctx.Request });
                object objRtn = mi.Invoke(obj, new object[] { ctx.Request });

                //if(mi.IsGenericMethod)
                //  mi.MakeGenericMethod(typeof(ht)).Invoke(obj, new object[] { ctx.Request });

                string outString = objRtn as string;

                if (null == outString || "" == outString.Trim())
                {
                    outString = "页面不存在！404 错误！";
                }

                
                //ctx.Server.Transfer(errorPath);
                //返回委托方法的结果到用户
                ctx.Response.Write(outString);
                ctx.Response.Flush();

                //ctx.RewritePath("~"+ errorPath);
//                ctx.RewritePath("~/aa.ax");
            //}

            //ctx.Response.Charset = "UTF-8";
            //ctx.Response.Write("哈哈");
            //ctx.Response.Flush();
        }
        catch (Exception ex)
        {
            //ctx.Response.Write(ex.ToString());
            //ctx.Response.Flush();

            ctx.Response.Write("页面不存在！404 错误！");
            ctx.Response.Flush();

            //throw ex;
        }
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
    #endregion

}